// 页面头部
import React, { useState, useEffect } from 'react';
import { Cascader } from 'antd';
import { CaretDownOutlined } from '#/utils/antdIcons';
import styles from './index.less';

const TRHead = ({
  value = [],
  options = [],
  fieldNames = {
    label: 'label',
    value: 'value',
    children: 'children',
  },
  onChange = () => {},
}) => {
  const [minWidth, setMinWidth] = useState(0);
  const [dropvis, setDropvis] = useState(false);
  const headRef = React.useRef();
  const cascaderRef = React.useRef();

  useEffect(() => {
    // 默认选中第一项
    if (options.length > 0) {
      const defaultOptions = getDefaultOptions(options, []);
      const defaultValues = defaultOptions.map((x) => x[fieldNames.value]);
      _onChange(defaultValues, defaultOptions);
    }
  }, [options]);

  function getDefaultOptions(arr, res) {
    const firsItem = arr?.[0];
    if (firsItem) {
      res.push(firsItem);
      if (firsItem[fieldNames.children]) {
        getDefaultOptions(firsItem[fieldNames.children], res);
      }
    }
    return res;
  }

  function _showSearch(inputValue, path) {
    return path.some((option) => option.label.indexOf(inputValue) > -1);
  }

  function _onChange(values, selectedOptions) {
    cascaderRef.current.blur();
    const pickerLabel = selectedOptions.map((x) => x[fieldNames.label]).join('/');
    setMinWidth(pickerLabel.length * 22 + 11 + 24 + 12);
    onChange?.(values, selectedOptions);
  }

  function _onPopupVisibleChange() {
    const isShow = !dropvis;
    setDropvis(isShow);
  }

  const _dropdownRender = (menus) => <div className={styles.tr_cascader_menus}>{menus}</div>;

  return (
    <div className={styles.tr_head} ref={headRef}>
      <Cascader
        ref={cascaderRef}
        value={value}
        options={options}
        fieldNames={fieldNames}
        className={styles.tr_cascader}
        style={{ minWidth }}
        allowClear={false}
        showSearch={{ _showSearch }}
        onPopupVisibleChange={_onPopupVisibleChange}
        dropdownRender={_dropdownRender}
        suffixIcon={
          <CaretDownOutlined
            className={styles.suffixIcon}
            style={{ transform: dropvis ? 'rotate(180deg)' : 'rotate(0deg)' }}
          />
        }
        onChange={_onChange}
      />
    </div>
  );
};

export default TRHead;
